package cn.qayy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.BasisDTO;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.po.Basis;
import cn.qayy.po.Policy;
import cn.qayy.service.IBasisService;
import cn.qayy.service.SynchronizationService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.BeanToMapUtils;
import cn.qayy.utils.DateUtils;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ResonseUtils;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu
 * 基础库 
 */
@Controller
@RequestMapping(value = "/basis/")
@SuppressWarnings("all")
public class BasisController {
	// 注入service
	@Resource(name = "basisServiceImpl")
	private IBasisService basisService = null;
	
	@Resource(name = "synchronizationImpl")
	private SynchronizationService synchronizationService = null;
	
	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件

	Logger log = Logger.getLogger(BasisController.class);
    
    /***
     * 通过Excel文件，批量导入
     * @param file 通过页面上传，页面上的文件名excelFile，和file参数名不一致，故需要@RequestParam做映射。
     * @param request
     * @return
     * http协议中，如果不指定Content-Type，则默认传递的参数就是application/x-www-form-urlencoded类型
     */
	@ResponseBody
	@RequestMapping(value = "upload")
	public Object upload(@RequestParam("excelFile") MultipartFile file,HttpServletRequest request) {
    	Msg msg = null;
    	int listSize = 0;//excel记录数
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(file,BasisDTO.class);
			
			if(map.get("fail") != null && !map.get("fail").isEmpty()) {
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
			} else {//DB持久化
				basisService.persistence(map,request,null);
				
				// 正常操作前台提示消息 
				if(map.get("totalCount") != null) {
					MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
					listSize = StringUtil.parseInt(msgInfo.getErr_num());
				}
				msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数："+listSize+"，总成功数："+listSize+"，请核查！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/***
	 * 查询列表
	 * @param dto
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectForList")
	public Object selectForList(BasisDTO dto,String pageNumber,String pageSize) {
		Msg msg = null;
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params = BeanToMapUtils.objectToMap_strong(dto);
			params.put("pageNumber", pageNumber);
			params.put("pageSize", pageSize);
			PageInfo<Basis> pageInfo = basisService.selectForList(params);
			msg = new Msg(Constant.SUCESSFUL_CODE,pageInfo);
		} catch(Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,e.getMessage());
		}
		return msg;
	}

	/***
	 * 页面新增、修改基础库
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "saveOrUpdate")
	public Object saveOrUpdate(BasisDTO dto,HttpServletRequest request) {
		String flag = (String) request.getParameter("flag");		
		Msg msg = null;
		dto.setIsUpdate(flag);
		try {
			//验证数据
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			if(map.get("fail") != null && !map.get("fail").isEmpty()) {
				/**
				 * 验证不通过，前台提示消息 
				 */
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
			} else {//验证通过，DB持久化
				basisService.persistence(map,request,null);
				msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数："+1+"，总成功数："+1+"，请核查！");
			}
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value = "selectByID")
	public Object selectByID(Integer id) {
		Msg msg = null;
		try {
			Basis basis = basisService.selectByID(id);
			msg = new Msg(Constant.SUCESSFUL_CODE,basis);
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	} 

	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<BasisDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(BasisDTO.class);
			String downloadPath = ExcelUtils.dataToExcelDxls("基础库",StringUtil.listToStrArray(CollectionConstant.basic_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui")
	public String ui() {
		return "basis_search";
	}
	/***
	 * 获取待复制的id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectIds")
	public Object selectIds(HttpServletResponse response,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		StringBuilder result=new StringBuilder();
		Msg msg = null;
		try {
			//获取缓存中的筛选条件
			Map<String, Object> params = (Map<String, Object>)DownLoadUtil.get("BasisDTO");
			if(params == null) {
				params = new HashMap<String, Object>();
				params.put("t", "1127");
			}
			List<Integer> list = basisService.selectIdsByMap(params);
			if(list != null && list.size()>0) {
				for (Integer id : list) {
					result.append(id+" ");
				}
				result.deleteCharAt(result.toString().length()-1);
			}
		} catch(Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			return msg;
		}
		json.put("ids", result.toString());
		ResonseUtils.writeResponseByJson(response, json);
		//封装成json返回给前台
		return null;
	}
	/***
	 * 通过Ids删除
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delByIds")
	public Object deletePlanByIDs(String id) {
		Msg msg = null;
		int doSize = 0;
		try {
			List<String> idList = StringUtil.strId2List(id," ");
			doSize = basisService.deleteByList(idList);
			/**
			 * 正常操作前台提示消息
			 */
			msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数：" + idList.size() + "，总成功数：" + doSize + "，请核查！");
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
}
